<?php

namespace App\Console\Commands\Cruise;

use App\Models\Cruise\CruiseCheckSelfDetailModel;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Remote\Rms\RmsUserRemote;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class FixSubmitShopSelfCheckRecordCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'shopSelfCheck:FixSubmitShopSelfCheckRecord';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '门店自检：修复已提交但未完成审批的数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $baseQuery = CruiseCheckSelfDetailModel::query()
                                               ->with("cruiseOrderProcessRel")
                                               ->where("templateType", CruiseTemplateModel::TYPE_8)
                                               ->where("status", CruiseCheckSelfDetailModel::STATUS_WAIT);

        $baseQuery->chunkById(
            100,
            function (Collection $collection) {
                $this->info("执行中...");
                $collection->each(function (CruiseCheckSelfDetailModel $cruiseCheckSelfDetailModel) {
                    $cruiseOrderProcessRel = $cruiseCheckSelfDetailModel->cruiseOrderProcessRel;
                    // 操作记录 - 获取提交人
                    $submit = $cruiseOrderProcessRel->where(
                        "step", CruiseOrderProcessModel::PROCESS_SUBMITTED
                    )->sortByDesc("id")->first();

                    // 更新完成数据
                    if ($submit) {
                        $submitUser = RmsUserRemote::getRmsUserByIds([$submit->createdByUid],
                                ['id', 'username'])[0] ?? [];

                        $this->info("执行中... 更新ID {$cruiseCheckSelfDetailModel->id}");
                        CruiseCheckSelfDetailModel::query()
                                                  ->where("id", $cruiseCheckSelfDetailModel->id)
                                                  ->update([
                                                      "status"         => CruiseCheckSelfDetailModel::STATUS_FINISH,
                                                      "finishTime"     => $submit->createdAt->timestamp,
                                                      "submitUid"      => attributeGet($submit, "id", 0),
                                                      "submitUsername" => attributeGet($submitUser, "username", ""),
                                                  ]);
                    }
                });

            });

        return 0;
    }
}
